package l1j.opqlo.NewSystem.地圖限時;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.utils.SQLUtil;

public class MapTimeTable {
	private static Logger _log = Logger.getLogger(MapTimeTable.class.getName());
	private final HashMap<Integer, MapTimeControl> _itemList = new HashMap<Integer, MapTimeControl>();

	private final ArrayList<Short> _mapList = new ArrayList<Short>();
	private static MapTimeTable _instance;

	public static MapTimeTable getInstance() {
		if (_instance == null) {
			_instance = new MapTimeTable();
		}
		return _instance;
	}

	/** 使用傳送卷軸 */
	public MapTimeControl getTimeControl(final int itemid) {
		return this._itemList.get(itemid);
	}

	/** 玩家是否在特殊地圖內 */
	public boolean isInMap(final short mapid) {
		return this._mapList.contains(mapid);
	}

	/** 讀取DB資料 */
	public void Load() {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM z_opqlo_teleportscroll");
			rs = pstm.executeQuery();
			this.LoadTable(rs);
		} catch (final SQLException e) {
			_log.log(Level.SEVERE,
					"error while creating z_opqlo_teleportscroll table", e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	/************************ 特殊地圖計時相關 **************************************/

	/** 讀取DB資料 */
	private void LoadTable(final ResultSet rs) throws SQLException {

		while (rs.next()) {

			final int itemid = rs.getInt("道具編號");
			final short mapid = rs.getShort("地圖編號");
			final int time = rs.getInt("時間限制");
			final MapTimeControl map = new MapTimeControl(mapid,
					rs.getInt("locx"), rs.getInt("locy"), time,
					rs.getInt("轉生限制"), rs.getInt("等級限制"), rs.getInt("最高等級"),
					rs.getInt("刪除道具"));
			this._itemList.put(itemid, map);
			if (time > 0) {
				this._mapList.add(mapid);
			}
		}

	}

}
